package cn.itsource.ymcc.producer;

import cn.itsource.ymcc.constant.CourseConstants;
import cn.itsource.ymcc.constant.MediaConstants;
import cn.itsource.ymcc.constant.OrderConstants;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.CourseOrderItem;
import cn.itsource.ymcc.result.JsonResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class OrderProducerImpl implements OrderProducer {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void sendSystemMessage(CourseOrder courseOrder) {
        String message = "您购买的"+courseOrder.getTitle()+"的课程已下单成功 订单号为"+courseOrder.getOrderNo();
        //发送消息
        rocketMQTemplate
                .syncSend(CourseConstants.TOPIC_COURSE_MESSAGE_SYSTEM + ":" + CourseConstants.TAGS_COURSE_MESSAGE_SYSTEM,
                        MessageBuilder.withPayload(JSON.toJSONString(message)).build());
    }

    @Override
    public void sendTransactionMessage(CourseOrder courseOrder, List<CourseOrderItem> items) {
        // 发送事务消息
        rocketMQTemplate.sendMessageInTransaction(OrderConstants.MQ_COURSEORDER_PAY_GROUP_TRANSACTION,
                OrderConstants.TOPIC_ORDER_MESSAGE_TRANSACTION + ":" + OrderConstants.TAGS_ORDER_MESSAGE_TRANSACTION,
                MessageBuilder.withPayload(JSON.toJSONString(courseOrder)).build(),
                items
        );
    }

    @Override
    public void sendDelayMessage(CourseOrder courseOrder) {
        //发送延迟消息
        rocketMQTemplate.syncSend(
                OrderConstants.TOPIC_ORDER_MESSAGE_DELAY
                        +":"+OrderConstants.TAGS_ORDER_MESSAGE_DELAY,
                MessageBuilder.withPayload(courseOrder.getOrderNo()).build(),
                2000,5);
    }
}
